import cv2, threading, time
from flask import Flask, render_template, Response 
# import simplejpeg as sjpeg 
import queue as Queue 
from turbojpeg import TurboJPEG

jpeg = TurboJPEG()

# bufferless VideoCapture
class VideoCapture:

  def __init__(self, name):
    self.cap = cv2.VideoCapture(name)
    self.cap.set(3, 1280) 
    self.cap.set(4, 720) 
    self.cap.set(5, 30) 
    self.q = Queue.Queue() 
    t = threading.Thread(target=self._reader) 
    t.daemon = True 
    t.start() # read frames as soon as they are available, keeping only most recent one
  def _reader(self): 
    while True: 
      ret, frame = self.cap.read() 
      if not ret: 
        break
      if not self.q.empty():
        try:
          self.q.get_nowait()   # discard previous (unprocessed) frame
        except Queue.Empty:
          pass
      self.q.put(frame)

  def read(self):
    return self.q.get()

cam = VideoCapture(-1)

def gen_frames():
    while True:
        frame = cam.read()
        #frame = sjpeg.encode_jpeg(frame, colorspace="BGR")
        frame = jpeg.encode(frame, quality=50)
        yield (b'--frame\r\n Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/video_feed')
def video_feed():
    return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)
